package com.boarsoft.boar.agent.apollo;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 修改自：com.ctrip.framework.apollo.core.signature.HmacSha1Utils
 * 
 * @author Mac_J
 */
public class HmacSha1Utils {

	private static final String ALGORITHM_NAME = "HmacSHA1";
	private static final String ENCODING = "UTF-8";

	// private final static Base64.Decoder decoder = Base64.getDecoder();
	private final static Base64.Encoder encoder = Base64.getEncoder();

	public static String signString(String stringToSign, String accessKeySecret) {
		try {
			Mac mac = Mac.getInstance(ALGORITHM_NAME);
			mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM_NAME));
			byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING));

			return new String(encoder.encode(signData), ENCODING);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
			throw new IllegalArgumentException(e.toString());
		}
	}
}